import { useState, useEffect } from 'react'
import { RefreshCw, Square, Trash2, Clock, CheckCircle, XCircle, AlertCircle, Play } from 'lucide-react'
import { toast } from 'react-hot-toast'
import type { GeneratorTask } from '@/types/dataGenerator'
import { dataGeneratorApi } from '@/services/dataGenerator'

interface TaskManagerProps {
  refreshTrigger?: number
}

export default function TaskManager({ refreshTrigger }: TaskManagerProps) {
  const [tasks, setTasks] = useState<GeneratorTask[]>([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    loadTasks()
  }, [refreshTrigger])

  useEffect(() => {
    // 定期刷新运行中的任务
    const interval = setInterval(() => {
      const runningTasks = tasks.filter(task => task.status === 'running' || task.status === 'starting')
      if (runningTasks.length > 0) {
        loadTasks()
      }
    }, 2000)

    return () => clearInterval(interval)
  }, [tasks])

  const loadTasks = async () => {
    try {
      setLoading(true)
      const tasksData = await dataGeneratorApi.getTasks()
      setTasks(tasksData)
    } catch (error) {
      console.error('加载任务列表失败:', error)
      toast.error('加载任务列表失败')
    } finally {
      setLoading(false)
    }
  }

  const stopTask = async (taskId: string) => {
    try {
      await dataGeneratorApi.stopTask(taskId)
      toast.success('任务已停止')
      loadTasks()
    } catch (error) {
      console.error('停止任务失败:', error)
      toast.error('停止任务失败')
    }
  }

  const deleteTask = async (taskId: string) => {
    try {
      await dataGeneratorApi.deleteTask(taskId)
      toast.success('任务已删除')
      loadTasks()
    } catch (error) {
      console.error('删除任务失败:', error)
      toast.error('删除任务失败')
    }
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'starting':
        return <Clock className="w-4 h-4 text-yellow-500" />
      case 'running':
        return <Play className="w-4 h-4 text-blue-500 animate-pulse" />
      case 'completed':
        return <CheckCircle className="w-4 h-4 text-green-500" />
      case 'failed':
        return <XCircle className="w-4 h-4 text-red-500" />
      case 'stopped':
        return <Square className="w-4 h-4 text-gray-500" />
      default:
        return <AlertCircle className="w-4 h-4 text-gray-400" />
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'starting':
        return '启动中'
      case 'running':
        return '运行中'
      case 'completed':
        return '已完成'
      case 'failed':
        return '失败'
      case 'stopped':
        return '已停止'
      default:
        return '未知'
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'starting':
        return 'text-yellow-600 bg-yellow-100'
      case 'running':
        return 'text-blue-600 bg-blue-100'
      case 'completed':
        return 'text-green-600 bg-green-100'
      case 'failed':
        return 'text-red-600 bg-red-100'
      case 'stopped':
        return 'text-gray-600 bg-gray-100'
      default:
        return 'text-gray-600 bg-gray-100'
    }
  }

  const formatDuration = (startTime: string, endTime?: string) => {
    const start = new Date(startTime)
    const end = endTime ? new Date(endTime) : new Date()
    const duration = Math.floor((end.getTime() - start.getTime()) / 1000)
    
    if (duration < 60) {
      return `${duration}秒`
    } else if (duration < 3600) {
      return `${Math.floor(duration / 60)}分${duration % 60}秒`
    } else {
      const hours = Math.floor(duration / 3600)
      const minutes = Math.floor((duration % 3600) / 60)
      return `${hours}时${minutes}分`
    }
  }

  const getProgress = (task: GeneratorTask) => {
    if (task.total_count === 0) return 0
    return Math.round((task.sent_count / task.total_count) * 100)
  }

  return (
    <div className="bg-white rounded-lg shadow-sm border p-6">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-lg font-semibold text-gray-900">生成任务管理</h2>
        <button
          onClick={loadTasks}
          disabled={loading}
          className="flex items-center space-x-2 px-3 py-1 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg disabled:opacity-50"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
          <span>刷新</span>
        </button>
      </div>

      {tasks.length === 0 ? (
        <div className="text-center py-8 text-gray-500">
          <Clock className="w-12 h-12 mx-auto mb-3 text-gray-300" />
          <p>暂无生成任务</p>
        </div>
      ) : (
        <div className="space-y-4">
          {tasks.map((task) => (
            <div key={task.task_id} className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center space-x-3">
                  {getStatusIcon(task.status)}
                  <div>
                    <div className="font-medium text-gray-900">
                      Topic: {task.topic}
                    </div>
                    <div className="text-sm text-gray-500">
                      任务ID: {task.task_id.slice(0, 8)}...
                    </div>
                  </div>
                </div>
                
                <div className="flex items-center space-x-2">
                  <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(task.status)}`}>
                    {getStatusText(task.status)}
                  </span>
                  
                  {task.status === 'running' && (
                    <button
                      onClick={() => stopTask(task.task_id)}
                      className="flex items-center space-x-1 px-2 py-1 text-xs bg-red-100 text-red-700 rounded hover:bg-red-200"
                    >
                      <Square className="w-3 h-3" />
                      <span>停止</span>
                    </button>
                  )}
                  
                  {['completed', 'failed', 'stopped'].includes(task.status) && (
                    <button
                      onClick={() => deleteTask(task.task_id)}
                      className="flex items-center space-x-1 px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200"
                    >
                      <Trash2 className="w-3 h-3" />
                      <span>删除</span>
                    </button>
                  )}
                </div>
              </div>

              {/* 进度条 */}
              <div className="mb-3">
                <div className="flex justify-between text-sm text-gray-600 mb-1">
                  <span>进度: {task.sent_count} / {task.total_count}</span>
                  <span>{getProgress(task)}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className={`h-2 rounded-full transition-all duration-300 ${
                      task.status === 'completed' ? 'bg-green-500' :
                      task.status === 'failed' ? 'bg-red-500' :
                      task.status === 'running' ? 'bg-blue-500' :
                      'bg-gray-400'
                    }`}
                    style={{ width: `${getProgress(task)}%` }}
                  />
                </div>
              </div>

              {/* 任务信息 */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                <div>
                  <span className="text-gray-500">开始时间:</span>
                  <div className="font-medium">
                    {new Date(task.start_time).toLocaleString()}
                  </div>
                </div>
                
                <div>
                  <span className="text-gray-500">运行时长:</span>
                  <div className="font-medium">
                    {formatDuration(task.start_time, task.end_time)}
                  </div>
                </div>
                
                <div>
                  <span className="text-gray-500">发送速率:</span>
                  <div className="font-medium">
                    {task.status === 'running' && task.sent_count > 0 ? (
                      `${Math.round(task.sent_count / (Date.now() - new Date(task.start_time).getTime()) * 60000)} msg/min`
                    ) : (
                      '-'
                    )}
                  </div>
                </div>
                
                <div>
                  <span className="text-gray-500">完成时间:</span>
                  <div className="font-medium">
                    {task.end_time ? new Date(task.end_time).toLocaleString() : '-'}
                  </div>
                </div>
              </div>

              {/* 错误信息 */}
              {task.error_message && (
                <div className="mt-3 p-3 bg-red-50 border border-red-200 rounded">
                  <div className="text-sm text-red-700">
                    <strong>错误信息:</strong> {task.error_message}
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
